{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "19a496c5-f467-4d7b-8c4a-6d62bb2a1013",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 读入图像\n",
    "import os \n",
    "import numpy as np\n",
    "from PIL import Image\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "img_path = 'image.jpg'\n",
    "img = Image.open(img_path)\n",
    "img_array = np.array(img)\n",
    "\n",
    "# 计算每个灰度级的频数和频率 \n",
    "gray_level = 256\n",
    "freq = np.zeros(gray_level)\n",
    "for i in range(img_array.shape[0]):   \n",
    "    for j in range(img_array.shape[1]):   \n",
    "        freq[img_array[i][j]] += 1\n",
    "freq_prob = freq / img_array.size   # 频率=频数/总像素数\n",
    "\n",
    "# 定义计算自信息的函数\n",
    "def self_info(freq_prob): \n",
    "    self_info = np.zeros(gray_level)\n",
    "    for i in range(gray_level):\n",
    "        if freq_prob[i] != 0:\n",
    "            self_info[i] = -np.log2(freq_prob[i])   # 自信息=-log2(频率)\n",
    "        else:\n",
    "            self_info[i] = 0\n",
    "    return self_info\n",
    "\n",
    "self_info = self_info(freq_prob)\n",
    "\n",
    "# 定义计算信息熵的函数\n",
    "def cal_entropy(freq_prob): \n",
    "    entropy = 0\n",
    "    for i in range(gray_level):\n",
    "        if freq_prob[i] != 0:\n",
    "            entropy -= freq_prob[i] * np.log2(freq_prob[i])  \n",
    "    return entropy\n",
    "\n",
    "entropy = cal_entropy(freq_prob)\n",
    "print('信息熵:', entropy)\n",
    "\n",
    "# 可视化\n",
    "plt.subplot(221)   # 摆放原图\n",
    "plt.imshow(img) \n",
    "\n",
    "plt.subplot(222)   # 摆放频数图\n",
    "plt.bar(range(gray_level), freq)\n",
    "\n",
    "plt.subplot(223)   # 摆放自信息图\n",
    "plt.bar(range(gray_level), self_info)\n",
    "\n",
    "plt.text(150, 8, '信息熵:%.3f' %entropy) # 在图中添加信息熵信息\n",
    "\n",
    "plt.show()  # 展示图像"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8192599c-5f45-491d-b03e-5955fc27eb0d",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": ""
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
